<?php namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Services\UserManager;
use App\Http\Services\Wechat\WechatLogin;
use App\Http\Services\Wechat\config;
use App\Http\Services\Wechat\WechatModelMsg;
use App\Http\Services\YunPian;
use App\Member;
use App\MemberCoupon;
use App\User;
use App\VerifyPhone;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Log;
use EasyWeChat\Foundation\Application;
use EasyWeChat\Support\Collection;
use EasyWeChat\Payment\Order;

class WechatController extends Controller
{
    public function index(){
        $app    = app("wechat");
        $server = $app->server;
        $user = $app->user;
        $menu = $app->menu;
        $server->setMessageHandler(function($message) use ($user) {
            Log::error("aaa=>".printf($message,true));
            $fromUser = $user->get($message->FromUserName);
            $openid   = $message->FromUserName;
            switch($message->MsgType){
                case 'event':
                    if($message->Event == "subscribe"){
                        return '您好，欢迎关注［吉日居酒屋］，2019年11月30日本店盛大开业，【回复您的手机号】即可获得20元优惠券！';
                    }

                    if($message->Event == "CLICK"){
                        switch ($message->EventKey){
                            case 'get_coupon':
                                $thatMember = Member::whereOpenId($openid)->first();
                                if(!$thatMember){
                                    return '您还未成为［吉日居酒屋］会员，请【回复您的手机号】领取优惠券！';
                                }else{
                                    $hasCouponCount = MemberCoupon::whereMemberId($thatMember->id)->whereStatus(0)->count();
                                    if($hasCouponCount > 5){
                                        return '不要太贪心呦，您已经有5张未使用的优惠券啦！';
                                    }else{
                                        $code = sprintf("%06d", rand(100000, 999999));
                                        while (true){
                                            $hasCode = MemberCoupon::whereCode($code)->whereStatus(0)->first();
                                            if(!$hasCode){
                                                break;
                                            }else{
                                                $code = sprintf("%06d", rand(100000, 999999));
                                            }
                                        }

                                        $newCoupon = new MemberCoupon();
                                        $newCoupon->member_id = $thatMember->id;
                                        $newCoupon->code = $code;
                                        $newCoupon->amount = 20;
                                        $newCoupon->status = 0;
                                        $newCoupon->end_time = date('Y-m-d H:i:s',time() + 7 * 86400);
                                        $newCoupon->save();
                                        return '恭喜您，成功获得20元优惠券（消费满100元可用），兑换码【'.$newCoupon->code.'】，有效期截止至'.$newCoupon->end_time.'，感谢您的支持！';
                                    }
                                }
                                break;
                        }
                    }
                    break;
                case 'text':
                    $content = $message->Content;
                    if(preg_match("/^1[345678]{1}\d{9}$/",$content)){
                        $a = self::getPhoneCode($content,$openid);
                        if($a){
                            return '您好，您将收到由［瑞志收银］发送的4位数字验证码，校验成功即可获得20元优惠券！';
                        }
                    }

                    if(is_numeric($content) && strlen($content) == 4){
                        /** @var VerifyPhone $verifyCodeByPhone */
                        $verifyCodeByPhone = VerifyPhone::whereEnsureSession($openid)->whereVerifyCode($content)->first();
                        if(!$verifyCodeByPhone || $verifyCodeByPhone->created_at->timestamp + 60 * 15 < time()){
                            return '验证码不匹配或已过期';
                        }
                        $verifyCodeByPhone -> delete();

                        $thatMember = Member::wherePhone($verifyCodeByPhone->phone)->first();
                        if(!$thatMember){
                            $thatMember = new Member();
                            $thatMember->open_id = $openid;
                            $thatMember->phone   = $verifyCodeByPhone->phone;
                            $thatMember->save();
                        }

                        $code = sprintf("%06d", rand(100000, 999999));
                        while (true){
                            $hasCode = MemberCoupon::whereCode($code)->whereStatus(0)->first();
                            if(!$hasCode){
                                break;
                            }else{
                                $code = sprintf("%06d", rand(100000, 999999));
                            }
                        }

                        $newCoupon = new MemberCoupon();
                        $newCoupon->member_id = $thatMember->id;
                        $newCoupon->code = $code;
                        $newCoupon->amount = 20;
                        $newCoupon->status = 0;
                        $newCoupon->end_time = date('Y-m-d H:i:s',time() + 7 * 86400);
                        $newCoupon->save();
                        return '恭喜您，成功获得20元优惠券（消费满100元可用），兑换码【'.$newCoupon->code.'】，有效期截止至'.$newCoupon->end_time.'，感谢您的支持！';

                    }else{
                        return "吉日居酒屋盛大开业啦！！！回复您的手机号即可获取优惠券哦！";
                    }
                    break;
            }
        });
        $buttons =[
                 [
                     "type"=>"click",
                      "name"=>"领取优惠券",
                      "key"=>"get_coupon"
                  ]
        ];
        $menu->add($buttons);
        $a = $server->serve();

        return $a;
    }

    public function getJsApiPacket(Request $request){
        $info = WechatLogin::getTicketByAccessToken();
        $jsapiTicket = $info->getTicket();

        $nonceStr = WechatLogin::createNonceStr();

        $timestamp = time();

        $url = urldecode($request->get('url'));

        Log::error('link===>'.$url);

        $config = new config();
        $appid  = $config->getAppid();

        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
        $signature = sha1($string);
        $signPackage = array(
            "appId"     => $appid,
            "nonceStr"  => $nonceStr,
            "timestamp" => $timestamp,
            "url"       => $url,
            "signature" => $signature,
            "rawString" => $string
        );
        return response()->json(['level'=>'success','data'=>$signPackage]);
    }

    public static function getPhoneCode($phone,$openid){
        $isAttact       = VerifyPhone::wherePhone($phone)->orderBy('created_at', 'desc')->first();

//        if ($isAttact && $isAttact->created_at->timestamp + 60 > time())
//            return response()->json(['level'=>'error','message' => '请等待60秒后再发送']);
//        if ($isAttact && $isAttact->created_at->timestamp + 60 * 60 * 24 > time())
//            return response()->json(['level'=>'error','message' => '不允许访问！']);

        $result = VerifyPhone::wherePhone($phone)->orderBy('created_at', 'desc')->first();
        if ($result && 60 + $result->created_at->timestamp > time())
            return response()->json(['level'=>'error','message' => '请等待60秒后再发送']);

        VerifyPhone::wherePhone($phone)->delete();

        $VerifyCodeByPhone                 = new VerifyPhone();
        $VerifyCodeByPhone->phone          = $phone;
        $VerifyCodeByPhone->verify_code    = sprintf("%04d", rand(1000, 9999));
        $VerifyCodeByPhone->ip             = '127.0.0.1';
        $VerifyCodeByPhone->ensure_session = $openid;

        $sendSms = new YunPian();
        $sendSms->sendBasicSmsWithCode($phone,$VerifyCodeByPhone->verify_code);

        $dataResult = $VerifyCodeByPhone->save();

        return true;
    }
    
    public function checkCode(Request $request){
        $code = $request->get('code');

        $thatMemberCoupon = MemberCoupon::whereCode(trim($code))->first();
        if(!$thatMemberCoupon){
            return response()->json(['level'=>'error',"message"=>"该兑换码不存在！"]);
        }

        if($thatMemberCoupon->status == 1){
            return response()->json(['level'=>'error',"message"=>"该兑换码已核销，请勿重复使用！"]);
        }

        $thatMember = Member::whereId($thatMemberCoupon->member_id)->first();
        $phone = $thatMember ? $thatMember->phone : '-';

        if(strtotime($thatMemberCoupon->end_time) < time()){
            return response()->json(['level'=>'error',"message"=>"该兑换码已过期！"]);
        }

        $thatMemberCoupon->status = 1;
        $thatMemberCoupon->save();

        return response()->json(['level'=>'success',"message"=>"兑换成功，请跟顾客核实手机号【".$phone."】,可减金额【￥".$thatMemberCoupon->amount."】！",'data'=>$thatMemberCoupon]);
    }
}